package com.example.netlib.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.netlib.BaseHttpResultBean;
import com.example.netlib.CallableService;
import com.example.netlib.DefaultHttpResultHandler;
import com.example.netlib.ErrorService;
import com.example.netlib.R;
import com.example.netlib.netwrapper.LocalHttpClientHolder;
import com.example.netlib.netwrapper.NetHttpClientHolder;
import com.szlanyou.thirdsdk.retrofit.client.HttpClient;
import com.szlanyou.thirdsdk.retrofit.client.RequestType;
import com.yanzhenjie.permission.AndPermission;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Demo主界面
 */
public class DemoHomeActivity extends BaseActivity {
    private static final String TAG = "DemoActivity";
    private String REQUEST_CODE_GET_REQUEST_TEST1 = "100";
    private String REQUEST_CODE_GET_REQUEST_TEST2 = "102";
    private String REQUEST_CODE_POST_REQUEST_TEST = "200";

    /**
     * 需要进行检测的权限数组
     * 为何MainActivity要申请这些权限，因为手机端不动态申请权限，无法写本地文件。
     */
    protected final String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        requestPermissionOnPhone();
    }

    private void requestPermissionOnPhone() {
        //这里使用RxPermission进行多组权限申请，会有问题。
        AndPermission.with(this)
                .runtime()
                .permission(needPermissions)
                .onGranted(permissions -> {
                })
                .onDenied(permissions -> {
                    Toast.makeText(DemoHomeActivity.this, "部分权限未开启，可能会影响部分功能使用。", Toast.LENGTH_LONG).show();
                })
                .start();
    }


    /**
     * GET请求测试
     * IHttpResultHandler的返回值为BaseHttpResultBean
     * @param view
     */
    public void getRequestTest1(View view) {
        HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("param1", "adssaf");
        map.put("param2", 2);
        httpClient.newRequestBuilder().type(RequestType.GET)
                .url(LocalHttpClientHolder.getInstance().getActionUrl().GET)
                .setParams(map)
                .addHeader("privateHeaderKey1","privateHeaderValue1")
                .addHeader("privateHeaderKey2",999999)
                .requestCode(REQUEST_CODE_GET_REQUEST_TEST1)
                .httpResultHandler(new DefaultHttpResultHandler<BaseHttpResultBean>(){})
                .request();
    }

    /**
     * 取消GET请求
     *
     * @param view
     */
    public void cancelGetRequestTest1(View view) {
        HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        httpClient.cancel(REQUEST_CODE_GET_REQUEST_TEST1);
    }

    /**
     * GET请求测试
     * IHttpResultHandler的返回值为BaseHttpResultBean中的Data
     *
     * @param view
     */
    public void getRequestTest2(View view) {
        /*HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("param1", "adssaf");
        map.put("param2", 2);
        httpClient.get(LocalHttpClientHolder.getInstance().getActionUrl().GET, map, new DefaultHttpResultHandler<BaseHttpResultBean>());*/

        //混合客户端测试
        HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("param1", "adssaf");
        map.put("param2", 2);
        httpClient.newRequestBuilder().type(RequestType.GET)
                .url(LocalHttpClientHolder.getInstance().getActionUrl().GET)
                .setParams(map)
                .addHeader("privateHeaderKey1","privateHeaderValue1")
                .addHeader("privateHeaderKey2",999999)
                .httpResultHandler(new DefaultHttpResultHandler<BaseHttpResultBean>(){})
                .requestCode(REQUEST_CODE_GET_REQUEST_TEST2)
                .request();

    }

    /**
     * POST请求测试
     *
     * @param view
     */
    public void postRequestTest(View view) {
        HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        //有参
        Map<String, Object> map = new HashMap<>();
        map.put("param1", "adssaf");
        map.put("param2", 2);

        httpClient.newRequestBuilder().type(RequestType.POST)
                .url(LocalHttpClientHolder.getInstance().getActionUrl().POST)
                .setParams(map)
                .addHeader("privateHeaderKey1","privateHeaderValue1")
                .addHeader("privateHeaderKey2",999999)
                .requestCode(REQUEST_CODE_POST_REQUEST_TEST)
                .httpResultHandler(new DefaultHttpResultHandler<BaseHttpResultBean>(){})
                .request();

    }


    public void cancelPostRequestTest(View view) {
        HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        httpClient.cancel(REQUEST_CODE_POST_REQUEST_TEST);
    }

    /**
     * 文件上传测试
     *
     * @param view
     */
    public void fileUploadTest(View view) {
        startActivity(new Intent(this, UploadFileActivity.class));
    }

    /**
     * 文件下载测试
     *
     * @param view
     */
    public void fileDownloadTest(View view) {
        startActivity(new Intent(this, FileDownloadActivity.class));
    }

    public void cancelAll(View view) {
        HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        httpClient.cancelAll();
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    public void cancelPart(View view) {
        HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
        httpClient.cancel(Set.of(REQUEST_CODE_GET_REQUEST_TEST1,REQUEST_CODE_POST_REQUEST_TEST));
    }

    public void syncRequestTest(View view){
        new Thread(){
            @Override
            public void run() {
                HttpClient httpClient = NetHttpClientHolder.getInstance().getHttpClient();
                Call<BaseHttpResultBean> call = httpClient.getService(CallableService.class).syncGetRequest();
                Response<BaseHttpResultBean> execute = null;
                try {
                    execute = call.execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(execute != null){
                    BaseHttpResultBean body = execute.body();
                    Log.d(TAG,"syncRequestTest " + body);
                }else{
                    Log.e(TAG,"response is null ");
                }
            }
        }.start();

    }

    @Override
    protected void onDestroy() {
        NetHttpClientHolder.getInstance().getHttpClient().cancelAll();
        NetHttpClientHolder.getInstance().getHttpClient().cancelAll();
        super.onDestroy();
    }

    public void cancelByPage(View view) {
        startActivity(new Intent(this, CancelByPageTestActivity.class));
    }

    public void errorTest(View view) {
        startActivity(new Intent(this, ErrorTestActivity.class));
    }
}